/*
 * Copyright 2017 Focus Technology, Co., Ltd. All rights reserved.
 */
/**
 * 
 */
package org.will.http.domain;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author wangwei-ww
 * @Date 2017/3/29 10:19
 * @Comment 
 */
public class CBHttpResult {
    private byte[] rawData;
    private int statusCode;
    private Map<String, String> responseHeaderMap = new HashMap<String, String>();
    private Map<String, String> setCoocies = new HashMap<String, String>();
    private static final String CONTENT_ENCODING_GZIP = "gzip";
    private String encoding = "utf-8";
    private String content = "";
    private static final int STATUS_CODE_OK = 200;
    private IOException ioException;

    public byte[] getRawData() {
        return rawData;
    }

    public void setRawData(byte[] rawData) {
        this.rawData = rawData;
    }

    public String getContent() {
        if (StringUtils.isEmpty(content)) {
            try {
                content = new String(rawData, encoding);
            }
            catch (UnsupportedEncodingException e) {
            }
        }
        return content;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public boolean isOk() {
        return statusCode == STATUS_CODE_OK;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public void addHeader(String headerName, String headerValue) {
        responseHeaderMap.put(headerName, headerValue);
    }

    public String getHeaderValue(String headerName) {
        return responseHeaderMap.get(headerName);
    }

    public void addSetCoocies(String setCoocies) {
        String tmp[] = setCoocies.split("=");
        this.setCoocies.put(tmp[0], tmp[1]);
    }

    public boolean isGzipEncoding() {
        return CONTENT_ENCODING_GZIP.equalsIgnoreCase(this.getHeaderValue(CBHttpHeaderName.CONTENT_ENCODING.getValue()));
    }

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public int getContentLength() {
        String lengthVal = this.getHeaderValue(CBHttpHeaderName.CONTENT_LENGTH.getValue());
        return lengthVal == null ? this.rawData.length : Integer.parseInt(lengthVal);
    }

    @Override
    public String toString() {
        return "status:" + statusCode + " size:" + getContentLength() + " content:" + getContent();
    }

    public boolean isIoException() {
        return ioException != null;
    }

    public void setIoException(IOException ioException) {
        this.ioException = ioException;
    }
}
